package com.ludaxu.google;

import java.util.LinkedList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

/**
 * 退出应用的方法1.kill进程,2,杀掉所有activity,3.广播杀掉所有activity,所有activity注册广播
 * 
 * @author ludaxu
 * 
 */
public class BaseActivity extends ActionBarActivity {
	// 可用管理运行的所有activity
	// LinkedList增删比较快,arraylist查询比较块
	public final static List<BaseActivity> mActivities = new LinkedList<BaseActivity>();
	private KillAllReceiver receiver;

	private class KillAllReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			finish();

		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		receiver = new KillAllReceiver();
		IntentFilter filter = new IntentFilter("com.ludaxu].google.killall");
		registerReceiver(receiver, filter);

		synchronized (mActivities) {
			mActivities.add(this);
		}
		init();
		initView();
		initActionBar();

	}

	protected void initView() {

	}

	protected void initActionBar() {

	}

	protected void init() {

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		synchronized (mActivities) {
			mActivities.remove(this);
		}
		if (receiver != null) {
			unregisterReceiver(receiver);
			receiver = null;
		}
	}

	/**
	 * 退出应用程序
	 */
	public void killAll() {
		// 复制了一份mActivities集合
		List<BaseActivity> copy;
		synchronized (mActivities) {
			copy = new LinkedList<BaseActivity>(mActivities);
		}
		for (BaseActivity activity : copy) {
			activity.finish();
		}
		// 杀死当前的进程
		android.os.Process.killProcess(android.os.Process.myPid());

	}

}
